package com.len.service;

import com.github.pagehelper.Page;
import com.len.entity.BannerEntity;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BannerService {

    @Resource
    private PageService pageService;

    @Resource
    private MongoTemplate mongoTemplate;

    public Page<BannerEntity> getList(Page<BannerEntity> page) {
        Query query = new Query();
        query.skip((long) (page.getPageNum() - 1) *page.getPageSize());
        query.limit(page.getPageSize());

        List<BannerEntity> list = mongoTemplate.find(query, BannerEntity.class);
        long total = pageService.count(query, BannerEntity.class);

        page.addAll(list);
        page.setTotal(total);
        return page;
    }

    public void add(BannerEntity bannerEntity){
        mongoTemplate.save(bannerEntity);
    }

    public void del(String id){
        mongoTemplate.remove(new Query(Criteria.where("id").is(id)), BannerEntity.class);
    }

    public BannerEntity getEntity(String id){
        return mongoTemplate.findById(id, BannerEntity.class);
    }

    public void update(BannerEntity bannerEntity) {
        Update update = new Update();
        update.set("name", bannerEntity.getName());
        update.set("url", bannerEntity.getUrl());
        mongoTemplate.updateFirst(new Query(Criteria.where("id").is(bannerEntity.getId())), update, BannerEntity.class);
    }
}
